package com.active.web;

import com.active.api.ActiveHandle;
import com.active.api.ActiveUserHandle;
import com.active.bean.ActiveInfo;
import com.active.bean.ActiveList;
import com.active.bean.ActiveUser;
import com.base.exception.NormalException;
import com.base.exception.NormalRuntimeException;
import com.base.util.JacksonUtil;
import com.base.util.RSAUtils;
import com.common.BaseController;
import com.common.util.AccessUtil;
import com.common.util.AjaxMessageUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.*;

@Controller
@RequestMapping("/active")
public class ActiveController extends BaseController{

    private Logger logger = LoggerFactory.getLogger(ActiveController.class);

    @Autowired
    private ActiveHandle activeHandle;

    @Autowired
    private ActiveUserHandle activeUserHandle;

    @Value("${security.private.key}")
    private String privateKey;
    @Value("${security.public.key}")
    private String publicKey;

    /**
     * 初始化和刷新
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/{to}")
    @ResponseBody
    Object activeHandle(@PathVariable ("to") String to,@RequestBody String body) throws Exception{
        System.out.println(request.getRemoteAddr());
        Enumeration<String> e = request.getHeaderNames();
        Object obj=null;
        body = new String(RSAUtils.decryptByPrivateKey(Base64.getDecoder().decode(body),privateKey),"UTF-8");
        switch(to){
            case SECURITY:
                obj = security(body);
                break;
            case PAGE:
                obj=page(body);
                break;
            case LISTID:
                obj=listId(body);
                break;
            case ALLNODES:
                obj=allNodes(body);
                break;
            case START:
                obj=start(body);
                break;
            case STOP:
                obj=stop(body);
                break;
            case PREV:
                obj=prev(body);
                break;
            case NEXT:
                obj=next(body);
                break;
            case ADD:
                obj= add(body);
                break;
            case DELETE:
                obj=delete(body);
                break;
            case WISDOM:
                obj=randomWisdom(body);
                break;
        }
        byte s[] = RSAUtils.encryptByPrivateKey(JacksonUtil.objToJson(obj).getBytes("UTF-8"),privateKey);
        String sign = RSAUtils.sign(s,privateKey);
        return AjaxMessageUtil.createSecurityInfoMessage(null,sign,Base64.getEncoder().encodeToString(s));
    }

    private Integer verifyUser(Map<String,Object> param) throws Exception{
        String key = (String) param.get("_key");
        if(key == null) throw new NormalRuntimeException("未登录！");
        Integer id = Integer.parseInt(new String(RSAUtils.decryptByPublicKey(Base64.getDecoder().decode(key),publicKey)));
        ActiveUser user = activeUserHandle.getUserById(id);
        if(user == null){
            throw new NormalRuntimeException("用户无权限！");
        }
        return user.getId();
    }

    private Object security(String body) throws Exception{
        Map<String,Object> param = JacksonUtil.jsonToObject(body,Map.class);
        String name = (String) param.get("name");
        String password = (String) param.get("password");
        if(name == null || password == null){
            throw new NormalException( "用户名或密码不能为空！");
        }
        ActiveUser user = activeUserHandle.getUserByPassword(name,password);
        if(user == null){
            throw new NormalException("用户名或密码错误！");
        }
        String id = user.getId().toString();
        return Base64.getEncoder().encodeToString(RSAUtils.encryptByPrivateKey(id.getBytes(),privateKey));
    }

    private Object page(String body) throws Exception{
        Map<String,Object> param = JacksonUtil.jsonToObject(body,Map.class);
        Integer currentPage = Integer.parseInt(param.get("currentPage").toString());
        return activeHandle.refreshListView(currentPage,verifyUser(param));
    }
    private Object listId(String body) throws Exception{
        Map<String,Object> param = JacksonUtil.jsonToObject(body,Map.class);
        Integer id = Integer.parseInt(param.get("id").toString());
        return activeHandle.getActiveListById(id,verifyUser(param));
    }
    private Object allNodes(String body) throws Exception{
        Map<String,Object> param = JacksonUtil.jsonToObject(body,Map.class);
        Integer activeListId = Integer.parseInt(param.get("activeListId").toString());
        return activeHandle.getActiveNodes(activeListId,verifyUser(param));
    }
    private Object start(String body) throws Exception{
        Map<String,Object> param = JacksonUtil.jsonToObject(body,Map.class);
        Integer activeListId = Integer.parseInt(param.get("activeListId").toString());
        int userId;
        activeHandle.startMission(activeListId,userId = verifyUser(param));
        Map<String,Object> result = new HashMap<>();
        result.put("activeList",activeHandle.getActiveListById(activeListId,userId));
        result.put("allNodes",activeHandle.getActiveNodes(activeListId,userId));
        return result;
    }
    private Object stop(String body) throws Exception{
        Map<String,Object> param = JacksonUtil.jsonToObject(body,Map.class);
        Integer activeListId = Integer.parseInt(param.get("activeListId").toString());
        activeHandle.stopMission(activeListId,verifyUser(param));
        Map<String,Object> result = new HashMap<>();
        int userId;
        result.put("activeList",activeHandle.getActiveListById(activeListId,userId = verifyUser(param)));
        result.put("allNodes",activeHandle.getActiveNodes(activeListId,userId));
        return result;
    }
    private Object prev(String body) throws Exception{
        Map<String,Object> param = JacksonUtil.jsonToObject(body,Map.class);
        Integer activeListId = Integer.parseInt(param.get("activeListId").toString());
        int userId;
        activeHandle.prevMission(activeListId,userId = verifyUser(param));
        Map<String,Object> result = new HashMap<>();
        result.put("activeList",activeHandle.getActiveListById(activeListId,userId));
        result.put("allNodes",activeHandle.getActiveNodes(activeListId,userId));
        return result;
    }
    private Object next(String body) throws Exception{
        Map<String,Object> param = JacksonUtil.jsonToObject(body,Map.class);
        Integer activeListId = Integer.parseInt(param.get("activeListId").toString());
        Integer state = Integer.parseInt(param.get("state").toString());
        int userId;
        activeHandle.nextMission(activeListId,state,userId = verifyUser(param));
        Map<String,Object> result = new HashMap<>();
        result.put("activeList",activeHandle.getActiveListById(activeListId,userId));
        result.put("allNodes",activeHandle.getActiveNodes(activeListId,userId));
        return result;
    }
    private Object add(String body) throws Exception{
        Map<String,Object> param=JacksonUtil.fastJsonToMap(body);
        String missionJson = (String) param.get("mission");
        String missionNodesJson = (String) param.get("missionNodes");
        AccessUtil.accessSuccess(missionJson!=null,"数据无效！");
        ActiveList activeList = JacksonUtil.jsonToObject(missionJson,ActiveList.class);
        List<ActiveInfo> list =null;
        if(missionNodesJson!=null){
            list = (List<ActiveInfo>) JacksonUtil.jsonToList(missionNodesJson,ActiveInfo.class);
        }
        AccessUtil.accessSuccess(activeList!=null,"数据无效！");
        AccessUtil.accessSuccess(list!=null,"请添加任务节点！");
        activeHandle.addMission(activeList,list,verifyUser(param));
        return "SUCCESS";
    }
    private Object delete(String body) throws Exception{
        Map<String,Object> param = JacksonUtil.jsonToObject(body,Map.class);
        Integer activeListId = Integer.parseInt(param.get("activeListId").toString());
        activeHandle.deleteMission(activeListId,verifyUser(param));
        return "SUCCESS";
    }

    public Object randomWisdom(String body) throws Exception{
        Map<String,Object> param = JacksonUtil.jsonToObject(body,Map.class);
        verifyUser(param);
        Integer num = Integer.parseInt(param.get("num").toString());
        return activeHandle.randomActiveWisdom(num);
    }

    private static final String SECURITY = "security";
    private static final String PAGE="refresh";
    private static final String LISTID="get";
    private static final String ALLNODES="nodes";
    private static final String START="start";
    private static final String STOP="stop";
    private static final String PREV="next";
    private static final String NEXT="prev";
    private static final String ADD="add";
    private static final String DELETE="delete";
    private static final String WISDOM="wisdom";

}
